#pragma once
#include<iostream>
#include<vector>
#include<semaphore.h>
#include<pthread.h>
#include<unistd.h>

using namespace std;

namespace ns_ring_queue
{
    template<class T>
    class RingQueue
    {
    public:
        RingQueue(int cap = 5)
            :_rq(cap)
            ,_cap(cap)
            ,_c_step(0)
            ,_p_step(0)
        {
            sem_init(&_blank_sem, 0, cap);
            sem_init(&_data_sem, 0, 0);

            pthread_mutex_init(&_c_mtx, nullptr);
            pthread_mutex_init(&_p_mtx, nullptr);
        }
        ~RingQueue()
        {
            sem_destroy(&_blank_sem);
            sem_destroy(&_data_sem);

            pthread_mutex_destroy(&_c_mtx);
            pthread_mutex_destroy(&_p_mtx);
        }
        void Push(const T& in)
        {
            //生产接口
            sem_wait(&_blank_sem);//p(空位置)
            pthread_mutex_lock(&_p_mtx);

            _rq[_p_step] = in;
            
            _p_step++;
            _p_step %= _cap;

            pthread_mutex_unlock(&_p_mtx);
            sem_post(&_data_sem);
            
        }
        void Pop(T* out)
        {
            //消费接口
            sem_wait(&_data_sem);//p(非空位置)
            pthread_mutex_lock(&_c_mtx);

            *out = _rq[_c_step];

            _c_step++;
            _c_step %= _cap;

            pthread_mutex_unlock(&_c_mtx);
            sem_post(&_blank_sem);
        }
    private:
        vector<T> _rq;
        int _cap;
        //生产者关心空位置
        sem_t _blank_sem;
        //消费者关心非空位置
        sem_t _data_sem;

        int _c_step;//消费者位置
        int _p_step;//生产者位置

        pthread_mutex_t _c_mtx;
        pthread_mutex_t _p_mtx;
    };
}